package com.example.tencentdemo.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;


@RestController
@CrossOrigin
public class identification {
    @Autowired
    private com.example.tencentdemo.service.Impl.identity identity;
    @RequestMapping("/handMovement")
    public String manualInput(@RequestParam("IdCard") String idCard,@RequestParam("Name") String Name, @RequestParam("imageFile") MultipartFile imageFile) {
        // 检查是否上传了文件
        if (imageFile.isEmpty()) {
            return "Error: 未上传图片文件";
        }

        try {
            // 将文件转换为Base64编码
            byte[] bytes = imageFile.getBytes();
            String base64Image = Base64.getEncoder().encodeToString(bytes);
            String s = identity.ManualInput(idCard, Name, base64Image);
            System.out.println(s);

            return s;
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: 文件处理失败";
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/autoInput")
    public String IdentifyInput( @RequestParam("imageFile") MultipartFile imageFile) throws IOException, TencentCloudSDKException {
        byte[] bytes = imageFile.getBytes();
        String base64Image = Base64.getEncoder().encodeToString(bytes);
        String jsonString = identity.IdentifyInput(base64Image);
        // 开始解析json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonString);

        // 从JSON中提取Name和IdNum字段的值
        String name = jsonNode.get("Name").asText();
        String IdCard = jsonNode.get("IdNum").asText();
        String Sex = jsonNode.get("Sex").asText();
        String Birth = jsonNode.get("Birth").asText();

        // 创建一个新的JSON对象并设置Name和IdNum字段的值
        JsonNode newNode = objectMapper.createObjectNode()
                .put("Name", name)
                .put("IdCard", IdCard)
                .put("Sex", Sex)
                .put("Birth", Birth);

        // 将新的JSON对象转换为字符串
        return objectMapper.writeValueAsString(newNode);
    }
}
